import GlobalStyle, { themes } from '@/design';
import useExternal from '@/hooks/useExternal';
import useThemeStore from '@/store/theme';
import { asyncFunction } from '@/utils';
import type { FC } from 'react';
import { useEffect, useRef, useState } from 'react';
import type { DefaultTheme } from 'styled-components';
import { ThemeProvider as Provider } from 'styled-components';

const setThemeFn = async (activeTheme: string, cb: (theme: DefaultTheme) => void) => {
  const { data } = await asyncFunction<{ default: DefaultTheme }>(themes[activeTheme]);
  data && cb(data.default);
};
const ThemeProvider: FC = (props) => {
  const { activeTheme } = useThemeStore();
  const initRef = useRef(false);
  const [theme, setTheme] = useState({});
  const [, { load }] = useExternal(`/css/theme-${activeTheme}.css`, { name: 'theme' });
  useEffect(() => {
    load();
    setThemeFn(activeTheme, setTheme);
  }, [load, activeTheme]);
  if (!initRef.current) {
    setThemeFn(activeTheme, setTheme);
    load();
    initRef.current = true;
  }
  return (
    <Provider theme={theme as DefaultTheme}>
      <GlobalStyle />
      {props.children}
    </Provider>
  );
};
export default ThemeProvider;
